package com.jfinal.plugin.avtivemq;

import javax.jms.*;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @createTime: 2018/12/19
 * @author: HingLo
 * @description: 目标池
 */
public class DestinationKit {


    /**
     * 目标集合,用于存放相同名称队列的目标对象,避免重复的去创建目标
     */
    private static final Map<String, Destination> DESTINATION_MAP = new ConcurrentHashMap<>(1);
    /**
     * 生产者集合,用户快速获取相同目标对象的生产者,减少创建生产者,使用时,直接从map中获取,更加快速
     */
    private static final Map<Destination, MessageProducer> PRODUCERS = new ConcurrentHashMap<>(1);
    /***
     *消费者集合缓存集合,用户快速的获取消费者对象,避免重复创建
     */
    private static final Map<Destination, MessageConsumer> CONSUMER = new ConcurrentHashMap<>(1);


    /**
     * 线程安全的创建 目标
     *
     * @param type    创建的类型(TOPICS,QUEUE)
     * @param name    对象名称
     * @param session session
     * @return 返回目标
     * @throws JMSException 异常
     */
    public static Destination createDestination(MessageType type, String name, Session session) throws JMSException {
        Destination destination = DESTINATION_MAP.get(name + type);
        if (destination == null) {
            if (type == MessageType.QUEUE) {
                destination = session.createQueue(name);
            } else if (type == MessageType.TOPICS) {
                destination = session.createTopic(name);
            } else {
                throw new RuntimeException("目标类型不争取,只能创建queue与topics两种类型");
            }
            DESTINATION_MAP.put(name + type, destination);
        }
        return destination;
    }

    /**
     * 生产者
     *
     * @param session     session
     * @param destination 目标对象
     * @return 返回结果
     * @throws JMSException
     */
    public static MessageProducer createMessageProducer(Session session, Destination destination) throws JMSException {
        // 创建生产者
        MessageProducer producer = PRODUCERS.get(destination);
        if (producer == null) {
            producer = session.createProducer(destination);
        }
        return producer;
    }

    /***
     * 消费者
     * @param session session
     * @param destination 目标对象
     * @return 返回结果
     * @throws JMSException
     */
    public static MessageConsumer createMessageConsumer(Session session, Destination destination) throws JMSException {
        // 创建生产者
        MessageConsumer consumer = CONSUMER.get(destination);
        if (consumer == null) {
            consumer = session.createConsumer(destination);
        }
        return consumer;
    }

}
